Page({
  data: {
    list: [{
        id: 1,
        name: 'Item 1'
      },
      {
        id: 2,
        name: 'Item 2'
      },
      {
        id: 3,
        name: 'Item 3'
      },
      {
        id: 4,
        name: 'Item 4'
      },
      {
        id: 5,
        name: 'Item 5'
      },
      {
        id: 6,
        name: 'Item 6'
      },
      // 更多项...
    ],
    draggingIndex: null,
    startY: 0,
    offsetY: 0
  },
  //长按
  onLongPress(e) {
    // console.log("onLongPress");
    const index = e.target.dataset.index;
    // console.log(index);
    this.setData({
      draggingIndex: index,
      startY: e.touches[0].clientY
    });
  },
  //拖动
  onTouchMove(e) {
    // console.log(e);
    if (this.data.draggingIndex === null) return;
    const touch = e.touches[0];
    const offsetY = touch.clientY - this.data.startY;
    this.setData({
      offsetY
    });
  },
  //移动结束
  onTouchEnd() {
    // console.log("onTouchEnd");
    if (this.data.draggingIndex === null) return;

    const {
      list,
      draggingIndex,
      offsetY
    } = this.data;
    const itemHeight = 50; // 假设每个项高度为50px
    let newIndex //= draggingIndex + Math.round(offsetY / itemHeight);

    // 根据偏移量的正负选择合适的取整函数
    if (offsetY < 0) {
      // 向上拖动，使用 Math.ceil 向上取整
      newIndex = draggingIndex + (Math.ceil(offsetY / itemHeight)+1);
    } else {
      // 向下拖动，使用 Math.floor 向下取整
      newIndex = draggingIndex + Math.round((offsetY > 25 && offsetY < 50 ? 50 : offsetY) / itemHeight);
    }

    console.log(newIndex+"-----");
    console.log(Math.round((offsetY > 25 && offsetY < 50 ? 100 : offsetY) / itemHeight));
    console.log(Math.ceil(offsetY / itemHeight)-1);
    if (newIndex <= 0) {
      newIndex = 0
    }

    if (newIndex >= 0) {
      const newList = [...list];
      // console.log(newList);
      const [draggedItem] = newList.splice(draggingIndex, 1);
      newList.splice(newIndex, 0, draggedItem);

      this.setData({
        list: newList,
        draggingIndex: null,
        offsetY: 0
      });
    } else {
      this.setData({
        draggingIndex: null,
        offsetY: 0
      });
    }
  }
});